import 'package:flutter/material.dart';

class DialogExamplePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Dialog 示例')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                //弹出对话框并等待其关闭
                bool? delete = await _showAlertDialog(context);
                if (delete == null) {
                  print("取消删除");
                } else {
                  print("已确认删除");
                  //... 删除文件
                }
              },
              child: Text('显示 AlertDialog'),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () async {
                int? choosse = await _showSimpleDialog(context);
                if (choosse != null) {
                  print("选择了：${choosse == 1 ? "中文简体" : "美国英语"}");
                }
              },
              child: Text('显示 SimpleDialog'),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () async {
                int? index = await _showCustomDialog(context);
                if (index != null) {
                  print("选择了：$index");
                }
              },
              child: Text('显示自定义 Dialog'),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              child: Text("对话框：复选框可点击）"),
              onPressed: () async {
                //弹出删除确认对话框，等待用户确认
                bool? deleteTree = await _showDeleteConfirmDialog(context);
                if (deleteTree == null) {
                  print("取消删除");
                } else {
                  print("同时删除子目录: $deleteTree");
                }
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              child: Text("显示底部菜单列表"),
              onPressed: () async {
                int? type = await _showModalBottomSheet(context);
                print(type);
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              child: Text("显示Loading弹框"),
              onPressed: () {
                _showLoadingDialog(context);
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              child: Text("显示日历选择器弹框"),
              onPressed: () async {
                var selectedDate = await _showDatePicker(context);
                if (selectedDate != null) {
                  print(
                    "选中的日期为: ${selectedDate.year}-${selectedDate.month}-${selectedDate.day}",
                  );
                } else {
                  print("用户取消了日期选择");
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  Future<bool?> _showAlertDialog(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('提示'),
          content: Text('您确定要删除当前文件吗?'),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }

  Future<int?> _showSimpleDialog(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: Text('请选择语言'),
          children: <Widget>[
            SimpleDialogOption(
              onPressed: () => Navigator.pop(context, 1),
              child: Text('中文简体'),
            ),
            SimpleDialogOption(
              onPressed: () => Navigator.pop(context, 2),
              child: Text('美国英语'),
            ),
          ],
        );
      },
    );
  }

  Future<int?> _showCustomDialog(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          child: Container(
            padding: EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ListTile(title: Text("请选择")),
                Expanded(
                  child: ListView.builder(
                    itemCount: 30,
                    itemBuilder: (BuildContext context, int index) {
                      return ListTile(
                        title: Text("$index"),
                        onTap: () => Navigator.pop(context, index),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<bool?> _showDeleteConfirmDialog(BuildContext context) {
    bool _withTree = false; //记录复选框是否选中
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text("您确定要删除当前文件吗?"),
              Row(
                children: <Widget>[
                  Text("同时删除子目录？"),
                  DialogCheckbox(
                    value: _withTree, //默认不选中
                    onChanged: (bool? value) {
                      //更新选中状态
                      _withTree = !_withTree;
                    },
                  ),
                ],
              ),
            ],
          ),
          actions: <Widget>[
            TextButton(
              child: Text("取消"),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              child: Text("删除"),
              onPressed: () {
                // 将选中状态返回
                Navigator.of(context).pop(_withTree);
              },
            ),
          ],
        );
      },
    );
  }

  // 弹出底部菜单列表模态对话框
  Future<int?> _showModalBottomSheet(BuildContext context) {
    return showModalBottomSheet<int>(
      context: context,
      builder: (BuildContext context) {
        return ListView.builder(
          itemCount: 30,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text("$index"),
              onTap: () => Navigator.of(context).pop(index),
            );
          },
        );
      },
    );
  }

  void _showLoadingDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false, //点击遮罩不关闭对话框
      builder: (context) {
        return AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              CircularProgressIndicator(),
              Padding(
                padding: const EdgeInsets.only(top: 26.0),
                child: Text("正在加载，请稍后..."),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<DateTime?> _showDatePicker(BuildContext context) {
    var date = DateTime.now();
    return showDatePicker(
      context: context,
      initialDate: date,
      firstDate: date,
      lastDate: date.add(
        //未来30天可选
        Duration(days: 30),
      ),
    );
  }
}

// 单独封装一个内部管理选中状态的复选框组件
class DialogCheckbox extends StatefulWidget {
  DialogCheckbox({Key? key, this.value, required this.onChanged});

  final ValueChanged<bool?> onChanged;
  final bool? value;

  @override
  _DialogCheckboxState createState() => _DialogCheckboxState();
}

class _DialogCheckboxState extends State<DialogCheckbox> {
  bool? value;

  @override
  void initState() {
    value = widget.value;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Checkbox(
      value: value,
      onChanged: (v) {
        //将选中状态通过事件的形式抛出
        widget.onChanged(v);
        setState(() {
          //更新自身选中状态
          value = v;
        });
      },
    );
  }
}
